﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace ERPWinFormWork.Material
{
    public partial class AddMaterialTable : Form
    {
        private int? _supplierId;
        private string _supplierName;
        
        /// <summary>
        /// 获取选中的物料信息
        /// </summary>
        public List<MaterialPropertiesOutput> SelectedMaterials { get; private set; } = new List<MaterialPropertiesOutput>();
        
        public AddMaterialTable(int? supplierId = null, string supplierName = null)
        {
            InitializeComponent();
            _supplierId = supplierId;
            _supplierName = supplierName;
       
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            // 添加复选框列到第一列
            if (dgvmaterialshow.Columns["SelectColumn"] == null)
            {
                var checkColumn = new DataGridViewCheckBoxColumn();
                checkColumn.Name = "SelectColumn";
                checkColumn.HeaderText = "选择";
                checkColumn.Width = 60;
                checkColumn.ReadOnly = false;
                checkColumn.TrueValue = true;
                checkColumn.FalseValue = false;
                dgvmaterialshow.Columns.Insert(0, checkColumn);
            }

            dgvmaterialshow.CurrentCellDirtyStateChanged += (s, e) =>
            {
                if (dgvmaterialshow.IsCurrentCellDirty)
                {
                    dgvmaterialshow.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            };
            tbxmaterialname.Text = string.Empty;
            tbxmaterialname.WaterText = "请输入物料名称";
            tbxmaterialname.SkinTxt.Text = string.Empty;
            tbxmaterialname.SkinTxt.WaterText = "请输入物料名称";

            cbxtype.SelectedIndex = -1;
            cbxtype.Text = string.Empty;
            cbxtype.WaterText = "请选择物料类型";

            cbxshuxing.SelectedIndex = -1;
            cbxshuxing.Text = string.Empty;
            cbxshuxing.WaterText = "请选择物料属性";

            cbxunit.SelectedIndex = -1;
            cbxunit.Text = string.Empty;
            cbxunit.WaterText = "请选择单位";

            // 设置窗体标题显示供应商信息
            if (!string.IsNullOrWhiteSpace(_supplierName))
            {
                this.Text = $"添加物料 - 供应商: {_supplierName}";
            }
            
            GetData();
            LoadTypeData();
            LoadPropertiesData();
            LoadunitData();
        }


        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }

        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;
        /// <summary>
        /// 物料显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<MaterialPropertiesOutput>>>(
                    endpoint: "Material/GetMaterialProperties",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 如果有供应商ID，过滤数据只显示该供应商的物料
                var filteredData = response.data;
                if (_supplierId.HasValue)
                {
                    filteredData = response.data.Where(x => x.Supplier_Id == _supplierId.Value).ToList();
                }

                // 将过滤后的数据绑定到 DataGridView
                dgvmaterialshow.DataSource = filteredData;

                // 初始化复选框列的值
                foreach (DataGridViewRow row in dgvmaterialshow.Rows)
                {
                    if (row.Cells.Count > 0)
                    {
                        row.Cells[0].Value = false;
                    }
                }
            }
        }
        /// <summary>
        /// 物料类型下拉框
        /// </summary>
        /// <returns></returns>
        private async void LoadTypeData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<Material_TypeDtos>>>(
                    endpoint: "Material/GetMaterialTypeShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    cbxtype.Items.Clear();
                    cbxtype.DisplayMember = "typeName";
                    cbxtype.ValueMember = "id";
                    cbxtype.DataSource = deptResponse.data;
                    cbxtype.SelectedIndex = -1;


                }


            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 物料属性下拉框
        /// </summary>
        /// <returns></returns>
        private async void LoadPropertiesData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<Material_PropertiesDtos>>>(
                    endpoint: "Material/GetMaterialPropertiesShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    cbxshuxing.Items.Clear();
                    cbxshuxing.DisplayMember = "propertiesName";
                    cbxshuxing.ValueMember = "id";
                    cbxshuxing.DataSource = deptResponse.data;
                    cbxshuxing.SelectedIndex = -1;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 单位下拉框
        /// </summary>
        private async void LoadunitData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<UnitModel>>>(
                    endpoint: "Material/GetUnitModelShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    cbxunit.Items.Clear();
                    cbxunit.DisplayMember = "unitName";
                    cbxunit.ValueMember = "id";
                    cbxunit.DataSource = deptResponse.data;
                    cbxunit.SelectedIndex = -1;


                }


            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        /// <summary>
        /// 物料信息的重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnchongzhi2_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置领料单名称输入框
                tbxmaterialname.Text = string.Empty;
                tbxmaterialname.WaterText = "请输入物料名称";
                tbxmaterialname.SkinTxt.Text = string.Empty;
                tbxmaterialname.SkinTxt.WaterText = "请输入物料名称";



                // 显示重置成功提示
                MessageBox.Show("物料信息查询条件已重置！所有输入已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 物料信息查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnchaxun_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(tbxmaterialname.Text))
            {
                queryParams["materialName"] = tbxmaterialname.Text;
            }

            // 类型ID（从下拉框选的值）
            if (cbxtype.SelectedValue != null)
            {
                queryParams["type_Id"] = ((int)cbxtype.SelectedValue).ToString();
            }

            // 单位ID（从下拉框选的值）
            if (cbxunit.SelectedValue != null)
            {
                queryParams["unit_Id"] = ((int)cbxunit.SelectedValue).ToString();
            }

            // 属性ID（从下拉框选的值）
            if (cbxshuxing.SelectedValue != null)
            {
                queryParams["properties_Id"] = ((int)cbxshuxing.SelectedValue).ToString();
            }
            // 调用改造后的 GetData，传入查询条件
            GetData(queryParams);
        }
        /// <summary>
        /// 点击确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnqueding2_Click(object sender, EventArgs e)
        {
            try
            {
                SelectedMaterials.Clear();
                
                // 遍历所有行，收集选中的物料
                foreach (DataGridViewRow row in dgvmaterialshow.Rows)
                {
                    var cellValue = row.Cells[0].Value; // 第一列是复选框列
                    bool isChecked = false;
                    
                    if (cellValue is bool)
                    {
                        isChecked = (bool)cellValue;
                    }
                    else if (cellValue != null)
                    {
                        bool.TryParse(cellValue.ToString(), out isChecked);
                    }
                    
                    if (isChecked && row.DataBoundItem is MaterialPropertiesOutput material)
                    {
                        SelectedMaterials.Add(material);
                    }
                }
                
                if (SelectedMaterials.Count == 0)
                {
                    MessageBox.Show("请至少选择一条物料记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择物料失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
